package com.funShopping.config.exception;

import com.funShopping.config.entity.ResultResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

/**
 * @program: funShopping
 * @description: 全局异常控制器
 * @author: talented_zhang
 * @create: 2024-03-30 16:17
 **/
@ControllerAdvice
@Slf4j
public class MyExceptionHandler {

    /**
    * @Description: 全局自动捕获异常
    * @Param:
    * @return:
    * @Author: talented_zhang
    * @Date: 2024/3/30
    */

    @ExceptionHandler(value =Exception.class)
    @ResponseBody
    public ResultResponse exceptionHandler(Exception e){
//        System.out.println("全局异常捕获>>>:"+e);
        /*判断操作权限*/
        if ("不允许访问".equals(e.getMessage()))
            return forbidden(e);
        return system(e);
    }

    /**
    * @Description: 自定义异常处理器
    * @Param:
    * @return:
    * @Author: talented_zhang
    * @Date: 2024/3/30
    */
    @ExceptionHandler(value = CustomThrowException.class)
    @ResponseBody
    public ResultResponse error(CustomThrowException e){
//        System.out.println("自定义抛出异常>>>:"+e);
        log.error(ResultResponse.CommonMessage.CUSTOM_Message.getMessage(),e.getMessage(),e);
        return ResultResponse.customException(e.getCode(),e.getMessage());
    }

    @ResponseStatus(HttpStatus.FORBIDDEN)
    private ResultResponse forbidden(Exception e){
        log.error(ResultResponse.CommonMessage.FORBIDDEN_Message.getMessage(),e.getMessage(),e);
        return ResultResponse.forbiddenException(e.getMessage());
    }

    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    private ResultResponse system(Exception e){
        log.error(ResultResponse.CommonMessage.INTERNAL_SERVER_ERROR_Message.getMessage(),e.getMessage(),e);
        return ResultResponse.systemException(e.getMessage());
    }
}
